package com.mosai.alignpro.adapter;

import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mosai.alignpro.BaseActivity;
import com.mosai.alignpro.EditDescribeActivity;
import com.mosai.alignpro.R;
import com.mosai.alignpro.entity.ImageInfo;
import com.mosai.alignpro.entity.PatientInfo;
import com.mosai.alignpro.event.AuditEvent;
import com.mosai.alignpro.event.EditingEvent;
import com.mosai.alignpro.util.DialogUtils;
import com.mosai.alignpro.util.IntentUtils;
import com.mosai.alignpro.util.TimeUtils;
import com.mosai.alignpro.util.Utils;
import com.mosai.alignpro.view.AddAngleDialog;
import com.mosai.alignpro.view.DiagnosisView;
import com.mosai.alignpro.view.NoPatientDialog;

import java.util.List;

/**
 * Created by Rays on 2020/3/24.
 */
public final class DiagnosisListViewHolder extends BaseViewHolder {
    private final DiagnosisView diagnosisView;
    private final TextView tvDoctorName, tvDate, tvRightName, tvImgDate, tvImageType, tvDiagnosisConclusion,
            tvConditionStatusTitle, tvConditionStatusDesc, tvDiagnosisResult, tvStatusAudited, tvScoliosisType;
    private final View btnEdit, btnConfirm, btnSave, btnCancelEdit;
    private final View layoutDoctorInfo, layoutResult, layoutConditionStatusTitle, layoutScoliosisType,
            diagnosisColorPreview, layoutConditionStatus, layoutOpPending, layoutOpEditing;
    private final ImageView ivDoctorAvatar, ivRightAvatar, ivAddAngle, ivSend;

    private final BaseActivity baseActivity;
    private final RequestOptions doctorOptions, patientOptions;
    private final DiagnosisListAdapter adapter;

    private final boolean isAssistant;

    DiagnosisListViewHolder(View itemView, BaseActivity baseActivity,
                            RequestOptions doctorOptions, RequestOptions patientOptions,
                            DiagnosisListAdapter adapter, boolean isAssistant) {
        super(itemView);
        this.baseActivity = baseActivity;
        this.doctorOptions = doctorOptions;
        this.patientOptions = patientOptions;
        this.adapter = adapter;
        this.isAssistant = isAssistant;
        diagnosisView = itemView.findViewById(R.id.diagnosisView);
        ivSend = itemView.findViewById(R.id.ivSend);
        btnEdit = itemView.findViewById(R.id.ivEdit);
        btnConfirm = itemView.findViewById(R.id.btnConfirm);
        btnSave = itemView.findViewById(R.id.btnSave);
        btnCancelEdit = itemView.findViewById(R.id.btnCancelEdit);
        layoutDoctorInfo = itemView.findViewById(R.id.layoutDoctorInfo);
        ivDoctorAvatar = itemView.findViewById(R.id.ivDoctorAvatar);
        tvDoctorName = itemView.findViewById(R.id.tvDoctorName);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivAddAngle = itemView.findViewById(R.id.ivAddAngle);
        ivRightAvatar = itemView.findViewById(R.id.ivRightAvatar);
        tvRightName = itemView.findViewById(R.id.tvRightName);
        tvImgDate = itemView.findViewById(R.id.tvImgDate);
        tvConditionStatusTitle = itemView.findViewById(R.id.tvConditionStatusTitle);
        tvConditionStatusDesc = itemView.findViewById(R.id.tvConditionStatusDesc);
        tvDiagnosisResult = itemView.findViewById(R.id.tvDiagnosisResult);
        tvStatusAudited = itemView.findViewById(R.id.tvStatusAudited);
        diagnosisColorPreview = itemView.findViewById(R.id.diagnosisColorPreview);
        layoutResult = itemView.findViewById(R.id.layoutResult);
        layoutConditionStatus = itemView.findViewById(R.id.layoutConditionStatus);
        layoutConditionStatusTitle = itemView.findViewById(R.id.layoutConditionStatusTitle);
        tvImageType = itemView.findViewById(R.id.tvImageType);
        layoutOpPending = itemView.findViewById(R.id.layoutOpPending);
        layoutOpEditing = itemView.findViewById(R.id.layoutOpEditing);
        layoutScoliosisType = itemView.findViewById(R.id.layoutScoliosisType);
        tvScoliosisType = itemView.findViewById(R.id.tvScoliosisType);
        tvDiagnosisConclusion = itemView.findViewById(R.id.tvDiagnosisConclusion);
    }

    @Override
    public void onBindViewHolder(ImageInfo item, List<Object> payloads) {
        for (Object payload : payloads) {
            if (DiagnosisListAdapter.PAYLOAD_DESCRIBE.equals(payload.toString())) {
                setDescribe(item);

                if (item.getImageType() == ImageInfo.IMAGE_TYPE_BACK) {
                    setConditionStatusText(item);
                    layoutScoliosisType.setVisibility(Utils.setScoliosisTypeText(tvScoliosisType, item) ? View.VISIBLE : View.GONE);
                }
            }
        }
    }

    @Override
    public void onBindViewHolder(ImageInfo item, int position) {
        diagnosisColorPreview.setVisibility(View.GONE);
        PatientInfo patientInfo = item.getPatientInfo();
        if (patientInfo == null) {
            Glide.with(baseActivity).clear(ivRightAvatar);
            ivRightAvatar.setImageResource(R.drawable.no_user);
            tvRightName.setText(R.string.no_patient);
        } else {
            Glide.with(baseActivity)
                    .load(patientInfo.getAvatar())
                    .placeholder(R.drawable.default_avatar)
                    .error(R.drawable.default_avatar)
                    .apply(patientOptions)
                    .into(ivRightAvatar);
            tvRightName.setText(patientInfo.getName());
        }
        tvImgDate.setText(TimeUtils.getTimeText(baseActivity, item.getCreationDate()));
        Utils.setImageTypeText(tvImageType, item);
        layoutScoliosisType.setVisibility(Utils.setScoliosisTypeText(tvScoliosisType, item) ? View.VISIBLE : View.GONE);

        boolean hasAngleInfo = Utils.hasAngleInfo(item);
        layoutConditionStatus.setVisibility(hasAngleInfo ? View.VISIBLE : View.GONE);
        if (item.isShowCondition()) {
            setConditionStatusText(item);
            layoutResult.setVisibility(View.GONE);
            layoutConditionStatusTitle.setVisibility(View.VISIBLE);
        } else {
            layoutResult.setVisibility(hasAngleInfo ? View.VISIBLE : View.GONE);
            layoutConditionStatusTitle.setVisibility(View.GONE);
            tvDiagnosisResult.setText(item.getNewAngleText());
        }
        setDescribe(item);

        diagnosisView.load(item);
        diagnosisView.setTag(diagnosisView.getId(), position);
        if (item.getImageType() == ImageInfo.IMAGE_TYPE_BACK) {
            diagnosisView.setOnAngleListener(null);
            layoutConditionStatus.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(item.getDescribe()) && (TextUtils.isEmpty(item.getNewDescribe()) || item.isNotEditDescribe())) {
                item.setNewDescribe(Utils.getDescribe(item, baseActivity));
            }
            setDescribe(item);
        } else {
            diagnosisView.setOnAngleListener((diagnosisView, angles, circlePoint) -> {
                boolean hasAngle = !angles.isEmpty();
                boolean hasData = hasAngle || circlePoint != null;
                diagnosisColorPreview.setVisibility(hasData ? View.VISIBLE : View.GONE);
                layoutConditionStatus.setVisibility(hasAngle ? View.VISIBLE : View.GONE);
                item.setAngles(angles);
                item.setCirclePoint(circlePoint);
                if (item.isShowCondition()) {
                    layoutResult.setVisibility(View.GONE);
                    if (item.getNewConditionStatus() == ImageInfo.CONDITION_STATUS_INIT || item.isEditing()) {
                        item.setNewConditionStatus(Utils.getConditionStatus(angles));
                    }
                    setConditionStatusText(item);
                } else {
                    layoutResult.setVisibility(hasAngle ? View.VISIBLE : View.GONE);
                    item.setNewAngleText(Utils.getAngleText(item));
                    tvDiagnosisResult.setText(item.getNewAngleText());
                }
                if (TextUtils.isEmpty(item.getDescribe()) && (TextUtils.isEmpty(item.getNewDescribe()) || item.isNotEditDescribe())) {
                    item.setNewDescribe(Utils.getDescribe(item, baseActivity));
                }
                setDescribe(item);
            });
        }

        auditStatus(item);
        changeStatus(item);

        ivAddAngle.setOnClickListener(v -> {
            if (item.isShowCondition()) {
                diagnosisView.addAngle(item, true);
            } else {
                new AddAngleDialog(baseActivity, (dialog, isAngle) -> {
                    if (diagnosisView.addAngle(item, isAngle)) {
                        dialog.dismiss();
                    }
                }).show();
            }
        });
        ivSend.setOnClickListener(v -> IntentUtils.goSelectDoctor(baseActivity, item));
        btnEdit.setOnClickListener(v -> {
            changeEditStatus(position, true);
            changeStatus(item);
        });
        btnSave.setOnClickListener(v -> baseActivity.postEvent(new AuditEvent(position, false)));
        btnConfirm.setOnClickListener(v -> {
            if (patientInfo == null) {
                new NoPatientDialog(baseActivity, (dialog, which) -> {
                    dialog.dismiss();
                    if (which == DialogInterface.BUTTON_NEUTRAL) {
                        // 关联病人图片
                        IntentUtils.goBindPatientImage(baseActivity, item);
                    } else if (which == DialogInterface.BUTTON_POSITIVE) {
                        // 直接确认
                        baseActivity.postEvent(new AuditEvent(position, true));
                    }
                }).show();
            } else {
                baseActivity.postEvent(new AuditEvent(position, true));
            }
        });
        btnCancelEdit.setOnClickListener(v ->
                DialogUtils.showCancelEditDialog(baseActivity, new DialogUtils.OnClickListener() {
                    @Override
                    protected void onClick(DialogInterface dialog, boolean isPositive) {
                        if (isPositive) {
                            changeEditStatus(position, false);
                            changeStatus(item);
                        }
                        dialog.dismiss();
                    }
                })
        );
        ivRightAvatar.setOnClickListener(v -> {
            if (patientInfo != null && adapter.isCanConfirm()) {
                IntentUtils.goPatientDetail(baseActivity, patientInfo);
            }
        });
        layoutConditionStatus.setOnClickListener(v -> EditDescribeActivity.startForResult(baseActivity, item));
    }

    private void setConditionStatusText(ImageInfo item) {
        tvConditionStatusTitle.setText(Utils.getConditionStatusText(item.getNewConditionStatus(), baseActivity));
    }

    private void setDescribe(ImageInfo item) {
        tvConditionStatusDesc.setText(item.getNewDescribe());
    }

    private void auditStatus(ImageInfo item) {
        tvStatusAudited.setVisibility(item.isAudited() ? View.VISIBLE : View.GONE);
        switch (item.getStatus()) {
            case ImageInfo.STATUS_AUDITED:
                Glide.with(baseActivity)
                        .load(item.getDoctorInfo().getAvatar())
                        .placeholder(R.drawable.default_avatar)
                        .error(R.drawable.default_avatar)
                        .apply(doctorOptions)
                        .into(ivDoctorAvatar);
                tvDoctorName.setText(item.getDoctorInfo().getName());
                tvDate.setText(baseActivity.getString(R.string.audit_date, item.getHistoryCreationTime()));
                break;
            case ImageInfo.STATUS_PENDING:
                break;
        }
    }

    private void changeEditStatus(int position, boolean isEditing) {
        diagnosisView.setEditing(isEditing);
        ImageInfo item = adapter.getData().get(position);
        if (!isEditing) {
            item.cancelEdit();
            adapter.notifyItemChanged(position);
        } else {
            item.setEditing(true);
        }
        baseActivity.postEvent(new EditingEvent(isEditing));
    }

    private void changeStatus(ImageInfo item) {
        diagnosisView.setHasEditPoint(item.isEditing());
        tvDiagnosisConclusion.setText(item.isAudited() ? R.string.diagnosis_conclusion : R.string.diagnosis_conclusion_ai);
        if (item.isEditing()) {
            layoutOpEditing.setVisibility(View.VISIBLE);
            layoutOpPending.setVisibility(View.GONE);
            if (item.getImageType() == ImageInfo.IMAGE_TYPE_BACK) {
                ivAddAngle.setVisibility(View.GONE);
            } else {
                ivAddAngle.setVisibility(View.VISIBLE);
            }
            return;
        }
        ivSend.setVisibility(adapter.isCanConfirm() ? View.VISIBLE : View.GONE);
        layoutOpEditing.setVisibility(View.GONE);
        layoutOpPending.setVisibility(View.VISIBLE);
        if (item.isAudited()) {
            btnEdit.setVisibility(isAssistant ? View.GONE : View.VISIBLE);
            btnConfirm.setVisibility(View.GONE);
            layoutDoctorInfo.setVisibility(View.VISIBLE);
        } else {
            btnEdit.setVisibility(View.VISIBLE);
            btnConfirm.setVisibility(!adapter.isCanConfirm() ? View.GONE : View.VISIBLE);
            layoutDoctorInfo.setVisibility(View.GONE);
        }
    }
}
